<template>
  <div class="dynamic-menu">
    <el-menu
      :default-active="activeMenu"
      class="el-menu-vertical"
      background-color="#304156"
      text-color="#fff"
      active-text-color="#409EFF"
      router>
      <template v-for="menu in menuTree" :key="menu.id">
        <!-- 有子菜单的情况 -->
        <el-sub-menu v-if="menu.children && menu.children.length > 0" :index="menu.id.toString()">
          <template #title>
            <el-icon v-if="menu.icon">
              <component :is="getIconComponent(menu.icon)" />
            </el-icon>
            <span>{{ menu.name }}</span>
          </template>
          <el-menu-item v-for="child in menu.children" :key="child.id" :index="child.path">
            <el-icon v-if="child.icon">
              <component :is="getIconComponent(child.icon)" />
            </el-icon>
            <span>{{ child.name }}</span>
          </el-menu-item>
        </el-sub-menu>

        <!-- 没有子菜单的情况 -->
        <el-menu-item v-else :index="menu.path">
          <el-icon v-if="menu.icon">
            <component :is="getIconComponent(menu.icon)" />
          </el-icon>
          <span>{{ menu.name }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { http } from "@/api";
import { ElMessage } from "element-plus";
import {
  Monitor,
  User,
  UserFilled,
  List,
  Setting,
  Cpu,
  Menu,
  Operation,
  Message,
  Document,
  View,
} from "@element-plus/icons-vue";

const route = useRoute();
const menuTree = ref([]);
const loading = ref(false);

// 当前激活的菜单
const activeMenu = computed(() => route.path);

// 图标映射
const iconMap = {
  Monitor: Monitor,
  User: User,
  UserFilled: UserFilled,
  List: List,
  Setting: Setting,
  Cpu: Cpu,
  Menu: Menu,
  Operation: Operation,
  Message: Message,
  Document: Document,
  View: View,
};

// 获取图标组件
const getIconComponent = (iconName) => {
  if (!iconName) return "div";
  return iconMap[iconName] || "div";
};

// 获取菜单数据
const fetchMenuTree = async () => {
  loading.value = true;
  try {
    const response = await http.get("/api/menus/tree");
    if (response.code === 200) {
      menuTree.value = response.data;
      // 等待DOM更新后再设置默认展开的菜单
    } else {
      ElMessage.error("获取菜单失败");
    }
  } catch (error) {
    console.error("获取菜单失败:", error);
    ElMessage.error("获取菜单失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchMenuTree();
});
</script>

<style scoped>
.dynamic-menu {
  height: 100%;
}

.el-menu-vertical {
  border-right: none;
  height: 100%;
}
</style>
